package com.vito.oa.act.extend.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.vito.act.model.ActExTableColsModel;
import com.vito.act.model.ActExTableModel;
import com.vito.act.service.ActExTableService;
import com.vito.act.service.impl.ActExTableServiceImpl;
import com.vito.base.authoriza.dao.SQLAdapterMapper;
import com.vito.base.model.DataGrid;
import com.vito.base.model.MyHashMap;
import com.vito.base.model.Result;
import com.vito.base.util.Contants;
import com.vito.base.util.Pty;
import com.vito.oa.act.constant.OaActContants;
import com.vito.oa.act.extend.dao.OaActExTableColsMapper;
import com.vito.oa.act.extend.dao.OaActExTableMapper;
import com.vito.oa.act.extend.model.OaActExTableColsModel;
import com.vito.oa.act.extend.model.OaActExTableModel;
@Service(group="OaActExTableServiceImpl")
public class OaActExTableServiceImpl extends ActExTableServiceImpl implements ActExTableService {
	private static final Logger log = LoggerFactory.getLogger(OaActExTableServiceImpl.class);
	private static String dialect="oracle";
	static{
		Pty pty  = null;
		try {
			pty = Pty.get("conf/jdbc");
		} catch (Exception e) {
		}
		if(pty!=null){
			dialect = pty.getProp("sql.dialect");
		}
	}
	@Autowired
	private OaActExTableMapper actExTableMapper;
	@Autowired
	private OaActExTableColsMapper actExTableColsMapper;
	@Autowired
	private SQLAdapterMapper sqlAdapterMapper;
	
	@Override
	public int saveActExTable(ActExTableModel actExTableModel) {
		return actExTableMapper.saveActExTable((OaActExTableModel)actExTableModel);
	}

	@Override
	public int deleteActExTable(ActExTableModel actExTableModel) {
		return actExTableMapper.deleteActExTable(actExTableModel);
	}

	@Override
	public int updateActExTable(ActExTableModel actExTableModel) {
		return actExTableMapper.updateActExTable(actExTableModel);
	}

	@Override
	public DataGrid<ActExTableModel> queryActExTableByPage(
			ActExTableModel actExTableModel) {
		DataGrid<ActExTableModel> data = new DataGrid<ActExTableModel>();
			data.setRows(actExTableMapper.queryActExTableByPage(actExTableModel));
			data.setTotal(actExTableModel.getTotal());
		return data;
	}

	@Override
	public List<MyHashMap<String, String>> queryActExTableTree(
			ActExTableModel actExTableModel) {
		return actExTableMapper.queryActExTableTree(actExTableModel);
	}

	@Override
	public List<ActExTableModel> queryTableList(ActExTableModel actExTableModel) {
		return actExTableMapper.queryTableList(actExTableModel);
	}

	@Override
	public List<MyHashMap<String, String>> queryTableListByBuss(
			Map<String, String> map) {
		return actExTableMapper.queryTableListByBuss(map);
	}

	@Override
	public Result addTableToDbByTableKey(String tableKey) {
		Result res = new Result();
		//查询到表的基本信息
		ActExTableModel table = new ActExTableModel();
		table.setTableKey(tableKey);
		List<ActExTableModel> table_list = actExTableMapper.queryTableList(table);
		if(table_list==null||table_list.size()==0){
			res.setCode(Result.CODE_NO_DATA);
			res.setMsg("未获取到表信息！");
			return res;
		}
		//取得表信息
		table = table_list.get(0);
		OaActExTableColsModel cols = new OaActExTableColsModel();
		cols.setTableKey(tableKey);
		List<OaActExTableColsModel> cols_list = actExTableColsMapper.queryActExTableCols(cols);
		if(cols_list==null||cols_list.size()==0){
			res.setCode(Result.CODE_NO_DATA);
			res.setMsg("未获取到字段信息，请为该表添加字段！");
			return res;
		}
		boolean isMainTable = true;
		for(ActExTableColsModel col:cols_list){
			if(col.getIsFk()!=null&&Contants.BASE_STATE.equals(col.getIsFk())){
				isMainTable = false;
				break;
			}
		}
		//创建表语句及主键语句
		StringBuffer sql = new StringBuffer();
		//表注释及字段注释语句
		StringBuffer comments = new StringBuffer();
		String tableName = Contants.TABLE_FIRST_NAME+table.getTableKey();
		if("mysql".equals(dialect)){
			sql.append("create table ");
			sql.append(tableName+"(");
			//存储主键名
			List<String> pk_list = new ArrayList<String>();
			for (int i = 0; i < cols_list.size(); i++) {
				ActExTableColsModel col = cols_list.get(i);
				sql.append(col.getColName()+" ");
				//判断字段类型
				if(col.getColType()!=null&&col.getColType().toUpperCase().equals(Contants.FORM_COL_TYPE_VARCHAR)){
					col.setColType(OaActContants.FORM_COL_TYPE_MYSQL_VARCHAR);
					if(col.getColLength()==0){
						res.setCode(Result.CODE_NO_DATA);
						res.setMsg("字段“"+col.getColName()+"”的长度设置错误！");
						return res;
					}
					int length = (int)col.getColLength();
					sql.append(col.getColType()+"("+length+")");
				}else if(col.getColType()!=null&&col.getColType().toUpperCase().equals(Contants.FORM_COL_TYPE_NUMBER)){
					col.setColType(OaActContants.FORM_COL_TYPE_MYSQL_NUMBER);
					sql.append(col.getColType());
				}else{
					sql.append(col.getColType());
				}
				//判断字段是否可为空
				/**注释原因：由于需求变化，流程驳回，终止表单不进行校验，表单内容可能为空！**/
//				if(col.getIsRequire()!=null && Contants.BASE_STATE.equals(col.getIsRequire())){
//					sql.append(" not null");
//				}
				if(col.getColNameCh()!=null&&!"".equals(col.getColNameCh())){
					sql.append(" COMMENT \'" + col.getColNameCh()+"\'");
//					comments.append("alter table "+tableName+" modify column "+col.getColName()+" "+col.getColType()+" comment '"+col.getColNameCh()+"'; ");
				}
				if(i<cols_list.size()-1){
					sql.append(",");
				}else{
					if(!isMainTable){
						sql.append(",task_id varchar(20)");
					}
				}
				if(col.getIsPk() != null && Contants.BASE_STATE.equals(col.getIsPk())){
					pk_list.add(col.getColName());
				}
			}
			//设定主键
			if(pk_list!=null&&pk_list.size()>0){
				sql.append(" , PRIMARY KEY(");
				for(int i=0;i<pk_list.size();i++){
					sql.append(pk_list.get(i));
					if(i<pk_list.size()-1){
						sql.append(",");
					}
				}
				sql.append(") ");
			}
			sql.append(") COMMENT \'"+table.getShortNameCh()+"\'");
			sql.append("; ");
		}else {
			comments.append("execute immediate 'comment on table "+tableName+" is ''"+table.getShortNameCh()+"''';");
			sql.append("execute immediate 'create table ");
			sql.append(tableName+"(");
			//存储主键名
			List<String> pk_list = new ArrayList<String>();
			for (int i = 0; i < cols_list.size(); i++) {
				ActExTableColsModel col = cols_list.get(i);
				sql.append(col.getColName()+" ");
				//判断字段类型
				if(col.getColType()!=null&&col.getColType().toUpperCase().equals(Contants.FORM_COL_TYPE_VARCHAR)){
					if(col.getColLength()==0){
						res.setCode(Result.CODE_NO_DATA);
						res.setMsg("字段“"+col.getColName()+"”的长度设置错误！");
						return res;
					}
					int length = (int)col.getColLength();
					sql.append(col.getColType()+"("+length+")");
				}else{
					sql.append(col.getColType());
				}
				//判断字段是否可为空
				/**注释原因：由于需求变化，流程驳回，终止表单不进行校验，表单内容可能为空！**/
//				if(col.getIsRequire()!=null && Contants.BASE_STATE.equals(col.getIsRequire())){
//					sql.append(" not null");
//				}
				if(i<cols_list.size()-1){
					sql.append(",");
				}else{
					if(!isMainTable){
						sql.append(",task_id varchar2(20)");
					}
				}
				if(col.getIsPk() != null && Contants.BASE_STATE.equals(col.getIsPk())){
					pk_list.add(col.getColName());
				}
				if(col.getColNameCh()!=null&&!"".equals(col.getColNameCh())){
					comments.append("execute immediate 'comment on column "+tableName+"."+col.getColName()+" is ''"+col.getColNameCh()+"''';");
				}
			}
			sql.append(")';");
			if(pk_list!=null&&pk_list.size()>0){
				sql.append("execute immediate 'alter table "+tableName+" add constraint PK_"+tableName+" primary key (");
				for(int i=0;i<pk_list.size();i++){
					sql.append(pk_list.get(i));
					if(i<pk_list.size()-1){
						sql.append(",");
					}
				}
				sql.append(")'; ");
			}
			sql.append(comments);
		}
		
		log.info("创建sql:"+sql.toString().toUpperCase());
		Map<String, String> map = new HashMap<String, String>();
		map.put("sql", sql.toString().toUpperCase()+"");
		map.put("databaseId", dialect);
		sqlAdapterMapper.updateDataBysql(map);
		res.setCode(Result.CODE_OK);
		res.setMsg("表：“"+tableName.toUpperCase()+"”创建成功！");
		return res;
	}
}



